<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';
require_once 'includes/functions.php';

$db = Database::getInstance();

// 初始化变量
$gameId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$game = null;

// 检查游戏是否存在
if ($gameId > 0) {
    $game = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "games WHERE id = ?", [$gameId]);
    
    if (!$game) {
        $_SESSION['flash_message'] = '游戏不存在';
        $_SESSION['flash_type'] = 'danger';
        header('Location: games.php');
        exit;
    }
}

// 获取游戏资源
try {
    $db->query("SELECT 1 FROM " . DB_PREFIX . "game_resources LIMIT 1");
    
    // 表存在，获取资源
    $resources = $db->fetchAll(
        "SELECT * FROM " . DB_PREFIX . "game_resources WHERE game_id = ? ORDER BY created_at DESC", 
        [$gameId]
    );
    
    // 按类型分组资源
    $imageResources = [];
    $audioResources = [];
    $configResources = [];
    
    foreach ($resources as $resource) {
        switch ($resource['type']) {
            case 'image':
                $imageResources[] = $resource;
                break;
            case 'audio':
                $audioResources[] = $resource;
                break;
            case 'config':
                $configResources[] = $resource;
                break;
        }
    }
} catch (Exception $e) {
    // 表不存在
    $resources = [];
    $imageResources = [];
    $audioResources = [];
    $configResources = [];
}

// 获取游戏数据
$playersCount = $db->fetchColumn(
    "SELECT COUNT(DISTINCT user_id) FROM " . DB_PREFIX . "game_records WHERE game_id = ?",
    [$gameId]
);

$totalPlays = $db->fetchColumn(
    "SELECT COUNT(*) FROM " . DB_PREFIX . "game_records WHERE game_id = ?",
    [$gameId]
);

$averageScore = $db->fetchColumn(
    "SELECT AVG(score) FROM " . DB_PREFIX . "game_records WHERE game_id = ?",
    [$gameId]
);

$achievements = $db->fetchAll(
    "SELECT * FROM " . DB_PREFIX . "achievements WHERE game_id = ? ORDER BY points DESC",
    [$gameId]
);
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-eye"></i> 游戏预览</h1>
    <div>
        <a href="game_resources.php?game_id=<?php echo $gameId; ?>" class="btn btn-primary">
            <i class="bi bi-archive"></i> 管理游戏资源
        </a>
        <a href="game_edit.php?id=<?php echo $gameId; ?>" class="btn btn-warning">
            <i class="bi bi-pencil"></i> 编辑游戏
        </a>
        <a href="games.php" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> 返回游戏列表
        </a>
    </div>
</div>

<div class="row mb-4">
    <div class="col-md-8">
        <!-- 游戏预览区域 -->
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <i class="bi bi-controller"></i> 游戏演示
                </div>
                <div>
                    <button type="button" class="btn btn-sm btn-outline-primary game-control-btn" id="fullScreenBtn">
                        <i class="bi bi-fullscreen"></i> 全屏
                    </button>
                </div>
            </div>
            <div class="card-body p-0">
                <div id="gamePreviewContainer" class="position-relative" style="height: 500px; background-color: #f0f0f0;">
                    <?php if (!empty($game['image'])): ?>
                        <div class="text-center p-3">
                            <img src="../<?php echo htmlspecialchars($game['image']); ?>" alt="游戏封面" class="img-fluid" style="max-height: 300px;">
                        </div>
                    <?php endif; ?>
                    
                    <div class="position-absolute top-50 start-50 translate-middle text-center">
                        <h3><?php echo htmlspecialchars($game['name']); ?></h3>
                        <p class="mb-4"><?php echo nl2br(htmlspecialchars($game['description'])); ?></p>
                        <button type="button" class="btn btn-lg btn-success" id="startGameBtn">
                            <i class="bi bi-play-fill"></i> 开始游戏演示
                        </button>
                    </div>
                    
                    <!-- 游戏界面 -->
                    <div id="gameInterface" class="position-absolute top-0 start-0 w-100 h-100 bg-white" style="display: none;">
                        <div class="h-100 d-flex flex-column">
                            <div class="p-2 bg-light d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge bg-primary">分数: <span id="gameScore">0</span></span>
                                    <span class="badge bg-info ms-2">时间: <span id="gameTimer">0</span>秒</span>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-danger" id="stopGameBtn">
                                    <i class="bi bi-stop-fill"></i> 停止演示
                                </button>
                            </div>
                            <div class="flex-grow-1 p-3" id="gameContent">
                                <?php if (count($imageResources) > 0): ?>
                                    <div id="gameCarousel" class="carousel slide w-100 h-100" data-bs-ride="carousel">
                                        <div class="carousel-inner h-100">
                                            <?php foreach ($imageResources as $index => $resource): ?>
                                                <div class="carousel-item <?php echo $index === 0 ? 'active' : ''; ?> h-100">
                                                    <img src="../<?php echo $resource['file_path']; ?>" class="d-block mx-auto h-100" alt="游戏资源">
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                        <?php if (count($imageResources) > 1): ?>
                                            <button class="carousel-control-prev" type="button" data-bs-target="#gameCarousel" data-bs-slide="prev">
                                                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                                <span class="visually-hidden">上一个</span>
                                            </button>
                                            <button class="carousel-control-next" type="button" data-bs-target="#gameCarousel" data-bs-slide="next">
                                                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                                <span class="visually-hidden">下一个</span>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-info h-100 d-flex align-items-center justify-content-center">
                                        <div class="text-center">
                                            <i class="bi bi-image display-1"></i>
                                            <p class="mt-3">请先上传游戏资源以启用预览功能。</p>
                                            <a href="game_resources.php?game_id=<?php echo $gameId; ?>" class="btn btn-primary">
                                                <i class="bi bi-upload"></i> 上传游戏资源
                                            </a>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 游戏资源预览 -->
        <?php if (!empty($resources)): ?>
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-images"></i> 游戏资源
            </div>
            <div class="card-body">
                <ul class="nav nav-tabs mb-3" id="resourcePreviewTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="img-tab" data-bs-toggle="tab" data-bs-target="#imgTab" type="button" role="tab" aria-controls="imgTab" aria-selected="true">
                            <i class="bi bi-image"></i> 图片 (<?php echo count($imageResources); ?>)
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="audio-tab" data-bs-toggle="tab" data-bs-target="#audioTab" type="button" role="tab" aria-controls="audioTab" aria-selected="false">
                            <i class="bi bi-music-note-beamed"></i> 音频 (<?php echo count($audioResources); ?>)
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="config-tab" data-bs-toggle="tab" data-bs-target="#configTab" type="button" role="tab" aria-controls="configTab" aria-selected="false">
                            <i class="bi bi-gear"></i> 配置 (<?php echo count($configResources); ?>)
                        </button>
                    </li>
                </ul>
                <div class="tab-content" id="resourcePreviewTabsContent">
                    <!-- 图片资源 -->
                    <div class="tab-pane fade show active" id="imgTab" role="tabpanel" aria-labelledby="img-tab">
                        <?php if (empty($imageResources)): ?>
                            <div class="alert alert-info">暂无图片资源</div>
                        <?php else: ?>
                            <div class="row row-cols-2 row-cols-md-4 g-3">
                                <?php foreach ($imageResources as $resource): ?>
                                    <div class="col">
                                        <div class="card h-100">
                                            <img src="../<?php echo $resource['file_path']; ?>" class="card-img-top" alt="游戏图片" style="height: 150px; object-fit: cover;">
                                            <div class="card-body p-2">
                                                <p class="card-text small"><?php echo htmlspecialchars($resource['filename']); ?></p>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- 音频资源 -->
                    <div class="tab-pane fade" id="audioTab" role="tabpanel" aria-labelledby="audio-tab">
                        <?php if (empty($audioResources)): ?>
                            <div class="alert alert-info">暂无音频资源</div>
                        <?php else: ?>
                            <div class="list-group">
                                <?php foreach ($audioResources as $resource): ?>
                                    <div class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <i class="bi bi-music-note-beamed"></i>
                                            <?php echo htmlspecialchars($resource['filename']); ?>
                                        </div>
                                        <audio controls style="height: 30px;">
                                            <source src="../<?php echo $resource['file_path']; ?>" type="audio/mpeg">
                                            您的浏览器不支持音频播放
                                        </audio>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- 配置资源 -->
                    <div class="tab-pane fade" id="configTab" role="tabpanel" aria-labelledby="config-tab">
                        <?php if (empty($configResources)): ?>
                            <div class="alert alert-info">暂无配置文件</div>
                        <?php else: ?>
                            <div class="list-group">
                                <?php foreach ($configResources as $resource): ?>
                                    <a href="../<?php echo $resource['file_path']; ?>" class="list-group-item list-group-item-action" target="_blank">
                                        <i class="bi bi-gear"></i>
                                        <?php echo htmlspecialchars($resource['filename']); ?>
                                        <small class="text-muted ms-2"><?php echo strtoupper(pathinfo($resource['filename'], PATHINFO_EXTENSION)); ?></small>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <div class="col-md-4">
        <!-- 游戏信息卡片 -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-info-circle"></i> 游戏信息
            </div>
            <div class="card-body">
                <h4><?php echo htmlspecialchars($game['name']); ?></h4>
                <div class="mb-2">
                    <span class="badge bg-primary"><?php echo htmlspecialchars($game['category']); ?></span>
                    <span class="badge bg-<?php echo $game['status'] === 'active' ? 'success' : 'secondary'; ?>"><?php echo $game['status'] === 'active' ? '活跃' : '禁用'; ?></span>
                </div>
                
                <p><?php echo nl2br(htmlspecialchars($game['description'])); ?></p>
                
                <div class="mb-3">
                    <div class="text-muted small mb-1">难度级别</div>
                    <div>
                        <?php echo str_repeat('<i class="bi bi-star-fill text-warning"></i>', $game['difficulty']); ?>
                        <?php echo str_repeat('<i class="bi bi-star text-warning"></i>', 5 - $game['difficulty']); ?>
                    </div>
                </div>
                
                <div class="mb-3">
                    <div class="text-muted small mb-1">适合年龄</div>
                    <div><?php echo $game['min_age'] . ' - ' . $game['max_age']; ?> 岁</div>
                </div>
                
                <div class="mb-3">
                    <div class="text-muted small mb-1">预计游戏时长</div>
                    <div><?php echo $game['play_time']; ?> 秒</div>
                </div>
                
                <div class="mb-3">
                    <div class="text-muted small mb-1">创建时间</div>
                    <div><?php echo date('Y-m-d H:i', strtotime($game['created_at'])); ?></div>
                </div>
                
                <div class="mb-3">
                    <div class="text-muted small mb-1">最后更新</div>
                    <div><?php echo date('Y-m-d H:i', strtotime($game['updated_at'])); ?></div>
                </div>
            </div>
        </div>
        
        <!-- 游戏统计卡片 -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-graph-up"></i> 游戏统计
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-4">
                        <div class="h3"><?php echo number_format($playersCount); ?></div>
                        <div class="text-muted small">玩家数</div>
                    </div>
                    <div class="col-4">
                        <div class="h3"><?php echo number_format($totalPlays); ?></div>
                        <div class="text-muted small">游玩次数</div>
                    </div>
                    <div class="col-4">
                        <div class="h3"><?php echo number_format($averageScore); ?></div>
                        <div class="text-muted small">平均分数</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 游戏规则卡片 -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-list-check"></i> 游戏规则
            </div>
            <div class="card-body">
                <?php if (empty($game['rules'])): ?>
                    <div class="alert alert-info">暂无游戏规则</div>
                <?php else: ?>
                    <?php echo nl2br(htmlspecialchars($game['rules'])); ?>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- 游戏成就卡片 -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-trophy"></i> 游戏成就
            </div>
            <div class="card-body">
                <?php if (empty($achievements)): ?>
                    <div class="alert alert-info">暂无游戏成就</div>
                <?php else: ?>
                    <div class="list-group">
                        <?php foreach ($achievements as $achievement): ?>
                            <div class="list-group-item">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h6 class="mb-1"><?php echo htmlspecialchars($achievement['name']); ?></h6>
                                    <span class="badge bg-warning"><?php echo $achievement['points']; ?> 分</span>
                                </div>
                                <p class="mb-1 small"><?php echo htmlspecialchars($achievement['description']); ?></p>
                                <small class="text-muted">条件: <?php echo htmlspecialchars($achievement['criteria']); ?></small>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- 游戏预览相关脚本 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    const startGameBtn = document.getElementById('startGameBtn');
    const stopGameBtn = document.getElementById('stopGameBtn');
    const fullScreenBtn = document.getElementById('fullScreenBtn');
    const gameInterface = document.getElementById('gameInterface');
    const gamePreviewContainer = document.getElementById('gamePreviewContainer');
    const gameScore = document.getElementById('gameScore');
    const gameTimer = document.getElementById('gameTimer');
    
    let gameTimerInterval;
    let gameTime = 0;
    let gameScoreValue = 0;
    
    // 开始游戏演示
    startGameBtn.addEventListener('click', function() {
        gameInterface.style.display = 'block';
        gameTime = 0;
        gameScoreValue = 0;
        updateGameDisplay();
        
        // 启动计时器
        gameTimerInterval = setInterval(function() {
            gameTime++;
            gameTimer.textContent = gameTime;
            
            // 随机增加分数，模拟游戏进行
            if (Math.random() > 0.7) {
                gameScoreValue += Math.floor(Math.random() * 10) + 1;
                gameScore.textContent = gameScoreValue;
            }
        }, 1000);
    });
    
    // 停止游戏演示
    stopGameBtn.addEventListener('click', function() {
        gameInterface.style.display = 'none';
        clearInterval(gameTimerInterval);
    });
    
    // 全屏按钮
    fullScreenBtn.addEventListener('click', function() {
        if (gamePreviewContainer.requestFullscreen) {
            gamePreviewContainer.requestFullscreen();
        } else if (gamePreviewContainer.mozRequestFullScreen) { // Firefox
            gamePreviewContainer.mozRequestFullScreen();
        } else if (gamePreviewContainer.webkitRequestFullscreen) { // Chrome, Safari, Opera
            gamePreviewContainer.webkitRequestFullscreen();
        } else if (gamePreviewContainer.msRequestFullscreen) { // IE/Edge
            gamePreviewContainer.msRequestFullscreen();
        }
    });
    
    // 更新游戏显示
    function updateGameDisplay() {
        gameScore.textContent = gameScoreValue;
        gameTimer.textContent = gameTime;
    }
});
</script>

<?php
require_once 'includes/footer.php';
?> 